// miniprogram/pages/servicePage/submitOrder/submitOrder.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    remarks: "",
    show: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const db = wx.cloud.database();
    const that = this;
    await db.collection("services").doc(`${options._id}`).get().then(res => {
      that.setData({
        goodsInfo: res.data
      })
    })
  },
  // 跳转到备注页面
  toRemarks: function () {
    wx.navigateTo({
      url: `./remarks/remarks?remarks=${this.data.remarks}`
    })
  },
  // 选择服务地址
  selectAddress: function () {
    this.setData({
      show: false
    })
  },
  // 取消选择地址状态
  cancelSelect: function () {
    this.setData({
      show: true
    })
  },
  // 新增服务地址
  addAddress: function () {
    wx.navigateTo({
      url: "../../addAddress/addAddress?isAdd=true"
    })
  },
  // 编辑服务地址
  edit: function (e) {
    wx.navigateTo({
      url: "../../addAddress/addAddress?index=" + e.currentTarget.dataset.index
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: async function () {
    this.setData({
      remarks: app.globalData.remarks
    })
    // 从数据库中读取用户地址
    const db = wx.cloud.database();
    await db.collection("userInfo").where({
      _openid: app.globalData.openId
    }).get().then(res => {
      this.setData({
        address: res.data[0].address
      })
    })

  },
  // 提交订单
  submitOrder: async function () {
    wx.showLoading({
      title: '提交中',
    })
    var formData = this.data.goodsInfo
    const db = wx.cloud.database();
    await db.collection("userInfo").where({
      _openid: app.globalData.openId
    }).get().then(res => {
      formData.orderId = res.data[0].order.length;
      formData.serving = true;
      formData.serviceAddress = this.data.determineAddress;
      formData.remarks = this.data.remarks;
    })
    await wx.cloud.callFunction({
      name: "update",
      data: {
        type: "order",
        openId: app.globalData.openId,
        formData: formData
      }
    }).then(() => {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '提交成功',
        showCancel: false,
        success() {
          wx.navigateBack()
        }
      })
    }).catch(console.error);
  },
  //确定地址
  determine: function (e) {
    this.setData({
      determineAddress: e.currentTarget.dataset.address
    });
    this.cancelSelect();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.remarks = "";
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})